package com.tping.design.singleton.register;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 生成随机组件
 *
 * @author xiai
 * @Date 2023/2/12 19:04
 * @Version 1.0
 */
public class ThreadSpecificSecureRandom {

    /**
     * 单例
     */
    private final static ThreadSpecificSecureRandom INSTANCE = new ThreadSpecificSecureRandom();

    private ThreadSpecificSecureRandom(){}

    public static ThreadSpecificSecureRandom getInstance(){
        return INSTANCE;
    }

    /**
     * 定义 线程本地存储SecureRandom对象
     */
    private static final ThreadLocal<SecureRandom> SECURE_RANDOM_THREAD_LOCAL = new ThreadLocal<SecureRandom>(){
        @Override
        protected SecureRandom initialValue() {
            SecureRandom secureRandom = null;
            try {
                secureRandom = SecureRandom.getInstance("SHA1PRNG");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                secureRandom = new SecureRandom();
            }
            return secureRandom;
        }
    };

    /**
     * 随机生成一个数
     *
     * @param bound
     * @return
     */
    public int nextInt(int bound) {
        SecureRandom secureRandom = SECURE_RANDOM_THREAD_LOCAL.get();
        return secureRandom.nextInt(bound);
    }
}
